package org.sifebint.backend.dao.folders;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.sifebint.backend.model.Folder;
import org.sifebint.backend.model.Report;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

class FolderRowMapper implements ParameterizedRowMapper<Folder> {
  
  private List<Folder> folders = new ArrayList<Folder>();
  
  @Override
  public Folder mapRow(ResultSet rs, int rowNum) throws SQLException {
    
    long folderId = rs.getLong("folder_id");
    
    if (folders.size() == 0 || folders.get(folders.size() - 1).getId() != folderId) {
      Folder folder = new Folder();
      folder.setId(folderId);
      folder.setName(rs.getString("folder_name"));
      folders.add(folder);
    }
    
    if (rs.getLong("report_id") != 0) {
      Report report = new Report();
      report.setId(rs.getLong("report_id"));
      report.setDataSourceId(rs.getLong("data_source_id"));
      report.setName(rs.getString("report_name"));
      report.setSql(rs.getString("sql_string"));
      folders.get(folders.size() - 1).getReports().add(report);
    }
    
    return null;
    
  }
  
  public List<Folder> getFolders() {
    return folders;
  }
  
}

public class FolderDaoImpl extends SimpleJdbcDaoSupport implements FolderDao {

  private String queryCreateFolder;
  
  private String queryUpdateFolder;
  
  private String queryDeleteFolder;
  
  private String queryGetFoldersWithReports;
  
  @Override
  public void createFolder(Folder folder) {
    getSimpleJdbcTemplate().update(queryCreateFolder, new Object[] { folder.getName() });
  }

  @Override
  public void deleteFolder(long folderId) {
    getSimpleJdbcTemplate().update(queryDeleteFolder, new Object[] { folderId });
  }

  @Override
  public List<Folder> getFoldersWithReports() {
    
    FolderRowMapper folderRowMapper = new FolderRowMapper();
    
    getSimpleJdbcTemplate().query(queryGetFoldersWithReports, folderRowMapper, new Object[] {});
          
    return folderRowMapper.getFolders();
    
  }

  @Override
  public void updateFolder(Folder folder) {
    getSimpleJdbcTemplate().update(queryUpdateFolder, new Object[] { folder.getName(), folder.getId() });
  }

  @Required
  public void setQueryCreateFolder(String queryCreateFolder) {
    this.queryCreateFolder = queryCreateFolder;
  }
  
  @Required
  public void setQueryUpdateFolder(String queryUpdateFolder) {
    this.queryUpdateFolder = queryUpdateFolder;
  }
  
  @Required
  public void setQueryDeleteFolder(String queryDeleteFolder) {
    this.queryDeleteFolder = queryDeleteFolder;
  }
  
  @Required
  public void setQueryGetFoldersWithReports(String queryGetFoldersWithReports) {
    this.queryGetFoldersWithReports = queryGetFoldersWithReports;
  }
  
}
